<template>
    <el-card>
        <el-button type="primary" @click="append(0)">新建分类</el-button>

        <template #header>
            <div>
                分类管理
            </div>
        </template>
        <el-tree
      style="max-width: 600px"
      :data="dataSource"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <a v-show="data.children" @click="append(data.id)">添加 </a>
            <a style="margin-left: 8px" @click="editTree(data,node)"> 编辑 </a>
            <a style="margin-left: 8px" @click="remove(node, data)"> 删除 </a>
          </span>
        </span>
      </template>
    </el-tree>
        
       
        <!-- 弹窗 -->
        <el-dialog v-model="dialogVisible" title="新增" width="500">
            <el-form label-width="80px" :model="addForm" :rules="rules" ref="formIns">

                <el-form-item label="分类名称" prop="category_name">
                    <el-input v-model="addForm.category_name"></el-input>
                </el-form-item>
                <el-form-item label="图片" prop="thumb">
                    <el-upload class="avatar-uploader" :action="api.UPLOAD" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="addForm.thumb" :src="api.baseURl + addForm.thumb" class="avatar" />

                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">
                                请上传jpg/png图片,并且小于200kb
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                
                <el-form-item label="排序顺序" prop="sort">
                    <el-input v-model="addForm.sort"></el-input>
                </el-form-item>

            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handlesubmit">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 编辑弹框 -->
        <el-dialog v-model="dialogVisible2" title="编辑" width="500">
            <el-form label-width="80px" :model="editForm" :rules="rules" ref="formIns2">
                <el-form-item label="分类名称" prop="category_name">
                    <el-input v-model="editForm.category_name"></el-input>
                </el-form-item>
                <el-form-item label="图片" prop="thumb">
                    <el-upload class="avatar-uploader" :action="api.UPLOAD" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="editForm.thumb" :src="api.baseURl + editForm.thumb" class="avatar" />

                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">
                                请上传jpg/png图片,并且小于200kb
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                
                <el-form-item label="排序顺序" prop="sort">
                    <el-input v-model="editForm.sort"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible2 = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit2">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 编辑弹框结束 -->
    </el-card>
</template>
<script setup lang="ts">
// 弹框

const open = () => {
    ElMessageBox.alert('This is a message', 'Title', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: 'OK',
        callback: (action: Action) => {
            ElMessage({
                type: 'info',
                message: `action: ${action}`,
            })
        },
    })
}
import { ref, reactive, onMounted } from 'vue';
import { getClassify, addClassify, delClassify, edtClassify } from '@/api/api';
import type { FormRules, FormInstance } from "element-plus"
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'
import { ElementPlus } from '@element-plus/icons-vue';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import api from "../api/url"
const iconData = Object.keys(ElementPlusIconsVue)
// 树形控件
import type Node from 'element-plus/es/components/tree/src/model/node'
interface Tree {
  id: number
  label: string
  children?: Tree[]
  sort:number
  thumb:string
}
// 查看

const dataSource = ref<Tree[]>()

const append = (id:number) => {
    addForm.pid=id;
    dialogVisible.value=true;
}

const remove = (node: Node, data: Tree) => {
  
}
// 编辑弹框触发事件
let editid=0;
const dialogVisible2=ref(false);
const formIns2 = ref<FormInstance>();
const editTree=(data:Tree,node:Node)=>{
    dialogVisible2.value=true;
    editForm.value={
    category_name: data.label,
    pid: node.parent.data.id||0,
    sort: data.sort,
    thumb: data.thumb,
    }
    console.log(editForm);
    
    editid=data.id;
}

const classifyData = ref<ClassifyData[]>([]);
onMounted(() => {
    getdata();
})
const pageSize = ref(50);
const total = ref(0);
const page = ref(1);
const getdata = async () => {
    const res = await getClassify({
        page: page.value,
        limit: pageSize.value,
       
    });
    classifyData.value = res.data.data;
    total.value = res.data.total
    console.log(classifyData);
    // 分类数据升维
    const treeData:Tree[]=[];
    classifyData.value.forEach((v)=>{
        if(v.pid===0){
            treeData.push({
                label:v.category_name,
                id:v.id as number,
                children:[],
                sort:v.sort,
                thumb:v.thumb
            })
        }else{
            let obj=treeData.find(o=>v.pid===o.id);
            (obj as Required<Tree>).children.push({
                label:v.category_name,
                id:v.id as number,
                sort:v.sort,
                thumb:""
            })
        }
    })
    console.log(treeData);
    treeData.sort((a,b)=>a.sort-b.sort)
    treeData.forEach(v=>{
        v.children?.sort((a,b)=>a.sort-b.sort)
    })
    dataSource.value=treeData;
    // const dataSource = ref<Tree[]>([

    // ])

}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response);
    addForm.thumb = response.url;

}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type != 'image/png') {
        ElMessage.error('图片格式必须为jpg或者png!')
        return false
    } else if (rawFile.size / 1024 > 200) {
        ElMessage.error('图片大小不能超过200k!')
        return false
    }
    return true
}
// 新增数据
const addForm = reactive<ClassifyData>({
    category_name: "",
    thumb: "",
    pid: 0,
    sort: 0,

});
const rules: FormRules = {
    label: { required: true, message: "请输入label", trigger: "blur" },
    icon: { required: true, message: "请输入icon", trigger: "blur" },
    path: { required: true, message: "请输入path", trigger: "blur" }
}
const dialogVisible = ref(false)
const formIns = ref<FormInstance>();
const handlesubmit = async () => {
    formIns.value?.validate(async (valid) => {
        if (valid) {
            const res = await addClassify(addForm)
            if (res.data.code === 200) {
                ElMessage.success("修改成功");
                dialogVisible.value = false;
                formIns.value?.resetFields();
                getdata();
            } else {
                ElMessage.error("修改失败")
            }
        }
    })
}
// 删除
const handleDelete = async (id: number) => {
    try {
        await ElMessageBox.confirm(
            '确认删除当前角色吗',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        const res = await delClassify(id);
        if (res.data.code === 200) {
            ElMessage.success("删除成功");
            getdata();
        } else {
            ElMessage.error("删除失败");
        }
    } catch (e) {
        ElMessage.info("取消删除")
    }
}


const Tree = ref(false);
const editForm = ref<ClassifyData>({
    id:0,
    category_name: "",
    thumb: "",
    pid: 0,
    sort: 0,
});


const handleSubmit2 = async() => {
    try {
        formIns2.value?.validate();
        const res = await edtClassify(editid, editForm.value)
            if (res.data.code === 200) {
                dialogVisible2.value = false;
                getdata();
                ElMessage.success("修改成功");
            } else {
                ElMessage.error("删除失败");
            }
    } catch (e) {
        
    }
    
}
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 106px;
    height: 106px;
    display: block;
    border: 1px dashed var(--el-border-color);
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 106px;
    height: 106px;
    text-align: center;
    border: 1px dashed var(--el-border-color);
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>